package com.zhu.salesmanagement;

import java.util.ArrayList;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.DataItem;
import com.zhu.salesmanagement.network.DownLoadCustomerData;
import com.zhu.salesmanagement.network.ParseData;
import com.zhu.salesmanagement.network.PostMethod;
import com.zhu.salesmanagement.network.PutCustomerData;
import com.zhu.salesmanagement.network.XMLRPCMethodCallback;
import com.zhu.salesmanagement.utils.Util;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 门店下载界面
 */

public class StoreDownLoadActivity extends Activity implements View.OnClickListener{

	public static final int REQUST_SUCCESSEND = 1;
	public static final int REQUST_SUCCESSEND_CITY = 2;
	public static final int REQUST_FAIL_OFFICESC = 3;
	public static final int REQUST_DWONLOADSUCCESSEND = 4;
	public static final int REQUST_DWONLOADFAIL = 5;

	private static final int MODE_SALESOFFICE = 2;
	private static final int MODE_PROVINCE = 3;

	private LinearLayout mBodyLinearLayout = null;
	private FrameLayout mFrameLayout = null;
	private TextView mNoneText = null;
	private TextView mLableText = null;
	private Spinner mSpinner = null;
	private View mPopView = null;
	private ImageView mImageView = null;
    private TextView mClewView = null;
    private AnimationDrawable mAnimation = null;
    private boolean isConnect = false;
    private ArrayList<DataItem> mOfficeList = null;
    private ArrayList<DataItem> mProvinceList = null;
    private ArrayList<DataItem> mCityList = null;
    private View mDownLoadView = null;
    private DownLoadCustomerData mDownLoadCustomerData = null;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_storedownload);

        setupViews();
        initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		mPopView = getLayoutInflater().inflate(R.layout.layout_popconnect, null);
        mPopView.setOnClickListener(null);

        mImageView = (ImageView)(mPopView.findViewById(R.id.popconnect_animationImage));
        mClewView = (TextView)(mPopView.findViewById(R.id.popconnect_animationText));

		findViewById(R.id.storedl_back).setOnClickListener(this);
		findViewById(R.id.storedl_topback).setOnClickListener(this);
		
		mBodyLinearLayout = (LinearLayout) findViewById(R.id.storedl_bodyView);
	    mFrameLayout = (FrameLayout)findViewById(R.id.storedl_layout);
	    mNoneText = (TextView)findViewById(R.id.storedl_text);
	    mSpinner = (Spinner) findViewById(R.id.storedl_sheng);
	    mLableText = (TextView)findViewById(R.id.storedl_labletext);
	    if(MODE_SALESOFFICE == Util.mVerifyUserResult.iDownloadRange){
	    	mSpinner.setVisibility(View.GONE);
	    	mLableText.setText(R.string.yingyesuo);
	    }
	}

	/**
	 * 显示联网动画
	 * @param textId 文本内容id
	 */
	private void showConnectAnimation(int textId){
		mClewView.setText(textId);
		mAnimation = (AnimationDrawable) mImageView.getBackground();
        mAnimation.setLevel(0);
        mAnimation.start();
        mFrameLayout.addView(mPopView);
        isConnect = true;
	}

	/**
	 * 移除联网动画
	 */
	private void removeConnectAnimation(){
		mAnimation.stop();
        mAnimation = null;
        mFrameLayout.removeView(mPopView);
        isConnect = false;
	}

	/**
	 * 点击事件处理
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.storedl_back:
				case R.id.storedl_topback:
					finish();
					break;
				case R.id.download_rowContent:
					mDownLoadView = arg0;
					DataItem item = (DataItem)arg0.getTag();
					if(MODE_SALESOFFICE == Util.mVerifyUserResult.iDownloadRange){
						startOfficeCustomerSC(item);
					}else if(MODE_PROVINCE == Util.mVerifyUserResult.iDownloadRange){
						startCityCustomerSC(item);
					}
					break;
			}
		}
	}

	/**
	 * 按键事件处理
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }

	/**
	 * 返回事件处理
	 */
	private boolean doBack(){
		if(isConnect){
			return true;
		}
		if(mDownLoadCustomerData != null && mDownLoadCustomerData.isSync()){
			return true;
		}
		return false;
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mDownLoadCustomerData = new DownLoadCustomerData(this, mHandler);
		if(MODE_SALESOFFICE == Util.mVerifyUserResult.iDownloadRange){
			startRequestEmployeeSalesOfficeSC();
		}else if(MODE_PROVINCE == Util.mVerifyUserResult.iDownloadRange){
			startRequestProvinceSC();
		}
	}

	/**
	 * 请求服务器端营业所列表数据
	 */
	private void startRequestEmployeeSalesOfficeSC(){
		showConnectAnimation(R.string.callyinyesuosc);
		PostMethod.requestEmployeeSalesOfficeSC(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
            	mOfficeList = ParseData.parseEmployeeSalesOfficeSC(result, StoreDownLoadActivity.this);
                if(mOfficeList != null){
                	mHandler.sendEmptyMessage(REQUST_SUCCESSEND);
                }else{
                	mHandler.sendEmptyMessage(REQUST_FAIL_OFFICESC);
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
	}

	/**
	 * 请求服务器端省列表数据
	 */
	private void startRequestProvinceSC(){
		showConnectAnimation(R.string.callprovincesc);
		PostMethod.requestProvinceSC(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
            	mProvinceList = ParseData.parseProvinceSC(result, StoreDownLoadActivity.this);
                if(mProvinceList != null){
                	mHandler.sendEmptyMessage(REQUST_SUCCESSEND);
                }else{
                	mHandler.sendEmptyMessage(REQUST_FAIL_OFFICESC);
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
	}

	/**
	 * 下载营业所门店数据
	 * @param item 下载营业所信息
	 */
	private void startOfficeCustomerSC(DataItem item){
		keepScreenOn();
		showConnectAnimation(R.string.downloadcustomersc);
		mDownLoadCustomerData.startSync(item.id);
	}

	/**
	 * 下载城市门店数据
	 * @param item 下载城市信息
	 */
	private void startCityCustomerSC(DataItem item){
		keepScreenOn();
		showConnectAnimation(R.string.downloadcustomersc);
		mDownLoadCustomerData.startSync(null, item.id);
	}

	/**
	 * 联网请求数据返回结果
	 */
	private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUST_SUCCESSEND:
                	removeConnectAnimation();
                	updateViewFromSalesOffices();
                    break;
                case REQUST_FAIL_OFFICESC:
                	removeConnectAnimation();
                	updateViewFromSalesOffices();
                	Actions.toastShort(StoreDownLoadActivity.this, getText(R.string.failcallyinyesuosc).toString());
                    break;
                case REQUST_DWONLOADSUCCESSEND:
                	clearKeepScreenOn();
                	updateSuccessImage();
                	removeConnectAnimation();
                	Actions.toastShort(StoreDownLoadActivity.this, getText(R.string.downloadsuccess).toString());
                	break;
                case REQUST_DWONLOADFAIL:
                	clearKeepScreenOn();
                	removeConnectAnimation();
                	Actions.toastShort(StoreDownLoadActivity.this, getText(R.string.downloadfail).toString());
                	break;
                case REQUST_SUCCESSEND_CITY:
                	removeConnectAnimation();
                	updateViewFromCitys();
                	break;
            }
        }
    };

    /**
	 * 根据营业所列表更新界面
	 */
    private void updateViewFromSalesOffices(){
    	mBodyLinearLayout.removeAllViews();
    	if(MODE_SALESOFFICE == Util.mVerifyUserResult.iDownloadRange){
    		if(mOfficeList != null && mOfficeList.size() > 0){
        		int size = mOfficeList.size();
        		for(int i = 0; i < size; i++){
        			mBodyLinearLayout.addView(getItemView(mOfficeList.get(i)));
        		}
        	}else{
        		mNoneText.setVisibility(View.VISIBLE);
        	}
    	}else if(MODE_PROVINCE == Util.mVerifyUserResult.iDownloadRange){
    		setupSpinner();
    	}
    }

    /**
	 * 根据城市列表更新界面
	 */
    private void updateViewFromCitys(){
    	mBodyLinearLayout.removeAllViews();
    	if(mCityList != null && mCityList.size() > 0){
    		int size = mCityList.size();
    		for(int i = 0; i < size; i++){
    			mBodyLinearLayout.addView(getItemView(mCityList.get(i)));
    		}
    		mNoneText.setVisibility(View.GONE);
    	}else{
    		mNoneText.setVisibility(View.VISIBLE);
    	}
    }

    /**
	 * 获取列表项界面
	 */
    private View getItemView(DataItem item){
    	View row = LayoutInflater.from(this).inflate(R.layout.download_listitem, null);
    	row.setOnClickListener(this);
    	row.setTag(item);
    	TextView name = (TextView) row.findViewById(R.id.download_name);
        name.setText(item.name);
    	return row;
    }

    /**
	 * 更新成功下载图片
	 */
    private void updateSuccessImage(){
    	ImageView iv = (ImageView)mDownLoadView.findViewById(R.id.download_image);
        iv.setImageResource(R.drawable.icon_ok);
    }

    public void onDestroy(){
    	super.onDestroy();
    	if(mDownLoadCustomerData != null){
    		mDownLoadCustomerData.destroy();
    		mDownLoadCustomerData = null;
    	}
    	if(mProvinceList != null){
    		mProvinceList.clear();
    		mProvinceList = null;
    	}
    	if(mOfficeList != null){
    		mOfficeList.clear();
    		mOfficeList = null;
    	}
    	if(mCityList != null){
    		mCityList.clear();
    		mCityList = null;
    	}
    }

    /**
	 * 更新省选择数据
	 */
    private void setupSpinner(){
    	if(mProvinceList != null && mProvinceList.size() > 0){
    		String[] name = new String[mProvinceList.size()];
            for (int i = 0; i < name.length; i++) {
                name[i] = mProvinceList.get(i).name;
            }
            ArrayAdapter adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, name);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            mSpinner.setAdapter(adapter);
            mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    TextView tv = (TextView)arg1;
                    tv.setTextColor(getResources().getColor(R.color.white));
                    DataItem item = mProvinceList.get(arg2);
                    startRequestCity(item.id);
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub

                }
            });
    	}else{
    		mNoneText.setVisibility(View.VISIBLE);
    	}
    }

    /**
	 * 根据省ID请求城市列表
	 * @param provinceId 省ID
	 */
    private void startRequestCity(String provinceId){
    	if(mCityList != null){
    		mCityList.clear();
    		mCityList = null;
    	}
    	showConnectAnimation(R.string.callcitysc);
		PostMethod.requestCitySC(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, provinceId, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
            	mCityList = ParseData.parseCitySC(result, StoreDownLoadActivity.this);
                if(mCityList != null){
                	mHandler.sendEmptyMessage(REQUST_SUCCESSEND_CITY);
                }else{
                	mHandler.sendEmptyMessage(REQUST_FAIL_OFFICESC);
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
	 * 保持屏幕常亮
	 */
    private void keepScreenOn(){
    	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
	 * 清除屏幕常亮
	 */
    private void clearKeepScreenOn(){
    	getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}
